package com.yifeixi.validation.config;

import cn.hutool.core.util.StrUtil;
import java.util.Locale;
import javax.servlet.http.HttpServletRequest;
import javax.validation.MessageInterpolator;
import lombok.AllArgsConstructor;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * 消息插值器
 *
 * @author YiFeiXi
 */
@AllArgsConstructor
public class MessageInterpolatorAdapter implements MessageInterpolator {

  private MessageInterpolator defaultInterpolator;

  @Override
  public String interpolate(String messageTemplate, Context context) {
    return defaultInterpolator.interpolate(messageTemplate, context, getRequestLocale());
  }

  @Override
  public String interpolate(String messageTemplate, Context context, Locale locale) {
    return defaultInterpolator.interpolate(messageTemplate, context, getRequestLocale());
  }

  private Locale getRequestLocale() {
    RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
    HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
    String header = request.getHeader("Accept-Language");
    if (StrUtil.equals(header, "en")) {
      return Locale.ENGLISH;
    }
    return Locale.CHINA;
  }
}
